<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客服对话系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.8;
            font-size: 14px;
        }

        .chat-container {
            height: 500px;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
        }

        .user-message {
            justify-content: flex-end;
        }

        .bot-message {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
        }

        .user-bubble {
            background: #007bff;
            color: white;
            border-bottom-right-radius: 5px;
        }

        .bot-bubble {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 5px;
        }

        .intent-tag {
            font-size: 12px;
            background: #e9ecef;
            padding: 2px 8px;
            border-radius: 10px;
            margin-top: 5px;
            display: inline-block;
        }

        .input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
        }

        .input-field {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
        }

        .input-field:focus {
            border-color: #007bff;
        }

        .send-button {
            background: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .send-button:hover {
            background: #0056b3;
        }

        .send-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }

        .session-info {
            font-size: 12px;
            color: #666;
            text-align: center;
            padding: 10px;
            background: #f8f9fa;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .session-actions {
            display: flex;
            gap: 10px;
        }

        .action-button {
            background: #6c757d;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 15px;
            cursor: pointer;
            font-size: 12px;
            transition: background 0.3s;
        }

        .action-button:hover {
            background: #5a6268;
        }

        .typing-indicator {
            display: inline-block;
            padding: 12px 16px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 18px;
            border-bottom-left-radius: 5px;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: #999;
            border-radius: 50%;
            animation: typing 1.4s infinite;
        }

        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
                opacity: 0.4;
            }
            30% {
                transform: translateY(-10px);
                opacity: 1;
            }
        }

        .system-message {
            text-align: center;
            margin: 10px 0;
        }

        .system-bubble {
            background: #e3f2fd;
            color: #1565c0;
            padding: 5px 10px;
            border-radius: 10px;
            font-size: 12px;
            display: inline-block;
        }

        .health-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .health-good {
            background-color: #28a745;
        }

        .health-bad {
            background-color: #dc3545;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🤖 智能客服对话系统</h1>
        <p>基于Spring AI + RAG技术，支持智能问答和意图识别</p>
    </div>

    <div class="chat-container" id="chatContainer">
        <div class="system-message">
            <div class="system-bubble">
                <span class="health-indicator health-good" id="healthIndicator"></span>
                <span id="healthStatus">系统正常运行中</span>
            </div>
        </div>
        <div class="message bot-message">
            <div class="message-bubble bot-bubble">
                您好！我是智能客服助手，请问有什么可以帮您？
            </div>
        </div>
    </div>

    <div class="session-info">
        <span>会话ID: <span id="sessionId">loading...</span></span>
        <div class="session-actions">
            <button class="action-button" id="loadHistoryButton">加载历史</button>
            <button class="action-button" id="clearHistoryButton">清除历史</button>
        </div>
    </div>

    <div class="input-container">
        <input type="text" class="input-field" id="messageInput" placeholder="请输入您的问题" autocomplete="off">
        <button class="send-button" id="sendButton">发送</button>
    </div>
</div>

<script>
    class ChatApp {
        constructor() {
            this.sessionId = this.generateSessionId();
            this.chatContainer = document.getElementById('chatContainer');
            this.messageInput = document.getElementById('messageInput');
            this.sendButton = document.getElementById('sendButton');
            this.sessionIdElement = document.getElementById('sessionId');
            this.loadHistoryButton = document.getElementById('loadHistoryButton');
            this.clearHistoryButton = document.getElementById('clearHistoryButton');
            this.healthIndicator = document.getElementById('healthIndicator');
            this.healthStatus = document.getElementById('healthStatus');
            
            this.init();
            this.checkHealth();
            // 定期检查健康状态
            this.healthCheckInterval = setInterval(() => this.checkHealth(), 30000);
        }

        init() {
            this.sessionIdElement.textContent = this.sessionId;

            this.sendButton.addEventListener('click', () => this.sendMessage());
            this.messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.sendMessage();
                }
            });

            this.loadHistoryButton.addEventListener('click', () => this.loadHistory());
            this.clearHistoryButton.addEventListener('click', () => this.clearHistory());
        }

        generateSessionId() {
            return 'session-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
        }

        async sendMessage() {
            const message = this.messageInput.value.trim();
            if (!message) return;

            this.addMessage('user', message);
            this.messageInput.value = '';
            this.setLoading(true);

            try {
                // 使用流式API
                await this.sendStreamMessage(message);
            } catch (error) {
                console.error('发送消息失败:', error);
                this.addMessage('bot', '抱歉，服务暂时不可用，请稍后重试。');
            } finally {
                this.setLoading(false);
            }
        }

        async sendStreamMessage(message) {
            const url = `/api/chat/stream?sessionId=${encodeURIComponent(this.sessionId)}&question=${encodeURIComponent(message)}`;
            
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            
            let botMessage = '';
            let messageElement = null;

            while (true) {
                const { done, value } = await reader.read();
                
                if (done) {
                    // 流式响应已完成，消息已经通过流式处理的方式添加到界面上，无需再次添加
                    break;
                }

                const chunk = decoder.decode(value, { stream: true });
                botMessage += chunk;
                
                // 每收到一个chunk更新一次消息
                if (messageElement) {
                    this.updateMessage(messageElement, botMessage);
                } else {
                    messageElement = this.addMessage('bot', botMessage);
                }
            }
        }

        addMessage(sender, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;

            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = `message-bubble ${sender}-bubble`;
            bubbleDiv.textContent = content;

            messageDiv.appendChild(bubbleDiv);
            this.chatContainer.appendChild(messageDiv);
            this.scrollToBottom();
            
            return bubbleDiv; // 返回气泡元素以便后续更新
        }

        updateMessage(element, content) {
            element.textContent = content;
            this.scrollToBottom();
        }

        async loadHistory() {
            try {
                this.addSystemMessage('正在加载历史记录...');
                
                const response = await fetch(`/api/chat/history/${encodeURIComponent(this.sessionId)}`);
                const data = await response.json();
                
                if (data.code === 200 && data.data && data.data.length > 0) {
                    // 清空当前聊天记录（保留系统消息）
                    const messages = this.chatContainer.querySelectorAll('.message');
                    messages.forEach(msg => {
                        if (!msg.classList.contains('system-message')) {
                            msg.remove();
                        }
                    });
                    
                    // 添加历史记录
                    data.data.forEach(msg => {
                        const sender = msg.role === 'user' ? 'user' : 'bot';
                        this.addMessage(sender, msg.content);
                    });
                    
                    this.addSystemMessage('历史记录加载完成');
                } else {
                    this.addSystemMessage('暂无历史记录');
                }
            } catch (error) {
                console.error('加载历史记录失败:', error);
                this.addSystemMessage('加载历史记录失败，请稍后重试');
            }
        }

        async clearHistory() {
            if (!confirm('确定要清除当前会话的所有聊天历史吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/chat/history/${encodeURIComponent(this.sessionId)}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    // 清空当前聊天记录（保留系统消息）
                    const messages = this.chatContainer.querySelectorAll('.message');
                    messages.forEach(msg => {
                        if (!msg.classList.contains('system-message')) {
                            msg.remove();
                        }
                    });
                    
                    this.addMessage('bot', '对话历史已清除，请问有什么可以帮您？');
                } else {
                    this.addSystemMessage('清除历史记录失败');
                }
            } catch (error) {
                console.error('清除历史记录失败:', error);
                this.addSystemMessage('清除历史记录失败，请稍后重试');
            }
        }

        async checkHealth() {
            try {
                const response = await fetch('/api/chat/health');
                const data = await response.json();
                
                if (response.ok && data.code === 200) {
                    this.healthIndicator.className = 'health-indicator health-good';
                    this.healthStatus.textContent = '系统正常运行中';
                } else {
                    throw new Error('健康检查失败');
                }
            } catch (error) {
                console.error('健康检查失败:', error);
                this.healthIndicator.className = 'health-indicator health-bad';
                this.healthStatus.textContent = '系统暂时不可用';
            }
        }

        addSystemMessage(content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'system-message';

            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = 'system-bubble';
            bubbleDiv.textContent = content;

            messageDiv.appendChild(bubbleDiv);
            this.chatContainer.appendChild(messageDiv);
            this.scrollToBottom();
        }

        showTypingIndicator() {
            const existingIndicator = document.getElementById('typingIndicator');
            if (existingIndicator) {
                return;
            }

            const messageDiv = document.createElement('div');
            messageDiv.className = 'message bot-message';
            messageDiv.id = 'typingIndicator';

            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = 'typing-indicator';

            const dotsDiv = document.createElement('div');
            dotsDiv.className = 'typing-dots';

            for (let i = 0; i < 3; i++) {
                const dot = document.createElement('div');
                dot.className = 'typing-dot';
                dotsDiv.appendChild(dot);
            }

            bubbleDiv.appendChild(dotsDiv);
            messageDiv.appendChild(bubbleDiv);
            this.chatContainer.appendChild(messageDiv);
            this.scrollToBottom();
        }

        hideTypingIndicator() {
            const indicator = document.getElementById('typingIndicator');
            if (indicator) {
                indicator.remove();
            }
        }

        setLoading(loading) {
            this.sendButton.disabled = loading;
            this.messageInput.disabled = loading;
            this.loadHistoryButton.disabled = loading;
            this.clearHistoryButton.disabled = loading;

            if (loading) {
                this.sendButton.textContent = '发送中...';
                this.showTypingIndicator();
            } else {
                this.sendButton.textContent = '发送';
                this.hideTypingIndicator();
            }
        }

        scrollToBottom() {
            this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
        }
    }

    // 初始化应用
    document.addEventListener('DOMContentLoaded', () => {
        new ChatApp();
    });
</script>
</body>
</html>